﻿// Copyright © 2011 Vladislav Borovikov
// http://vividkit.codeplex.com/

namespace VividKit.Controls
{
	using System.Collections.ObjectModel;
	using System.Collections.Specialized;
	using System.Windows;
	using System.Windows.Data;

	public sealed class PageBarItemCollection : ObservableCollection<PageBarItem>
	{
		private PageBar owner;

		internal void ReflectItemVisibility(PageBarItem item)
		{
			this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(item.IsVisible ? NotifyCollectionChangedAction.Add : NotifyCollectionChangedAction.Remove, item, IndexOf(item)));
		}

		internal void SetOwner(PageBar owner)
		{
			this.owner = owner;

			foreach (var item in this)
			{
				EnsureDataContextBinding(item);
			}
		}

		protected override void InsertItem(int index, PageBarItem item)
		{
			base.InsertItem(index, item);
			EnsureDataContextBinding(item);
		}

		protected override void SetItem(int index, PageBarItem item)
		{
			base.SetItem(index, item);
			EnsureDataContextBinding(item);
		}

		private void EnsureDataContextBinding(PageBarItem item)
		{
			if (this.owner != null)
			{
				item.Owner = this.owner;

				if (item.ReadLocalValue(FrameworkElement.DataContextProperty) == DependencyProperty.UnsetValue)
				{
					item.SetBinding(FrameworkElement.DataContextProperty, new Binding("Page.DataContext") { Source = this.owner });
				}
			}
		}
	}
}